package com.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.blog.pojo.*;
import com.blog.service.BlogService;
import com.blog.service.BlogTagService;
import com.blog.service.ThumbsUpService;
import com.blog.service.ViewsService;
import com.blog.utils.IpUtils;
import com.blog.utils.UUIDUtils;
import com.github.pagehelper.PageInfo;
import javafx.scene.control.Alert;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.session.Session;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-04-21 16:45
 * FileName: BolgController
 * Description: 博客控制层
 */
@RestController
@RequestMapping("blog")
@Slf4j
public class BlogController extends BaseController{
    @Resource
    private BlogService blogService;
    @Resource
    private ViewsService viewsService;
    @Resource
    private BlogTagService blogTagService;


    private static final String REST_URL_PREFIX = "http://SERVICE-USER";

    /***
     * 博客发布
     * @param blog
     * @param tag
     * @return
     */
    @PostMapping("/PublishBlog/{tag}/{uid}")
    public String PublishBlog(@RequestBody Blog blog,@PathVariable("tag") int[] tag,@PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        log.info("提交的博客信息为{}",blog);
        blog.setBlogId(UUIDUtils.getNumber());
        User user=checkUser(uid);
        //判断用户是否登录
        if(user!=null){
            blog.setUser(user);
            log.info("用户已登录,ID为:{}",user.getUid());
            blogTagService.insertBlogTags(tag,blog.getBlogId());
            blogService.PublishBlog(blog);
            object.put("flag",true);
        }else{
            log.info("用户未登录!");
            object.put("flag",false);
        }
        return object.toJSONString();
    }

    /***
     * 博客保存
     * @param blog
     * @param tag
     * @return
     */
    @PutMapping("/SaveBlog/{tag}/{uid}")
    public String SaveBlog(@RequestBody Blog blog,@PathVariable("tag") int[] tag,@PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        log.info("提交的博客信息为{}",blog);
        LocalDateTime localDateTime= LocalDateTime.now();
        blog.setUpdateTime(localDateTime);
        User user=checkUser(uid);
        //判断用户是否登录
        if(user!=null){
            blog.setUser(user);
            log.info("用户已登录,ID为:{}",user.getUid());
            if(blog.getBlogId()==null){
                blog.setBlogId(UUIDUtils.getNumber());
                blogTagService.insertBlogTags(tag,blog.getBlogId());
                blogService.PublishBlog(blog);
                object.put("flag",true);
            }else{
                blogTagService.delByBlogId(blog.getBlogId());
                blogTagService.insertBlogTags(tag,blog.getBlogId());
                blogService.UpdateBlog(blog);
                object.put("flag",true);
            }
            object.put("flag",true);
        }else{
            log.info("用户未登录!");
            object.put("flag",false);
        }
        return object.toJSONString();
    }
    /***
     * 博客分类分页-模糊查询
     * @param pageNumber
     * @param pageSize
     * @param title
     * @param type_id
     * @return
     */
    @GetMapping("/queryAll/type/{pageNumber}/{pageSize}")
    public  String QueryByTypeAll(
            @Param("开始页数") @PathVariable("pageNumber") Integer pageNumber,
            @Param("总页数") @PathVariable("pageSize") Integer pageSize,
            @Param("标题") @RequestParam(defaultValue = "null") @PathVariable("title") String title,
            @Param("类型") @RequestParam(defaultValue = "0") @PathVariable("type_id") Integer type_id) {

        JSONObject object =new JSONObject();
        PageInfo<Blog> PageInfo = blogService.queryByTypePageAll(pageNumber,pageSize,type_id,title);
        object.put("blogList",PageInfo.getList());
        object.put("pages",PageInfo.getPages());
        object.put("blogCount",PageInfo.getTotal());
        return object.toJSONString();
        };

    /***
     * 博客标签分页
     * @param pageNumber
     * @param pageSize
     * @param tag_id
     * @return
     */
    @GetMapping("/queryAll/tag/{pageNumber}/{pageSize}")
    public  String QueryByTagAll(
            @Param("开始页数") @PathVariable("pageNumber") Integer pageNumber,
            @Param("总页数") @PathVariable("pageSize") Integer pageSize,
            @Param("标签") @RequestParam(defaultValue = "0") @PathVariable("tag_id") Integer tag_id) {

        JSONObject object =new JSONObject();
        PageInfo<Blog> PageInfo = blogService.queryByTagPageAll(pageNumber,pageSize,tag_id);
        object.put("blogList",PageInfo.getList());
        object.put("pages",PageInfo.getPages());
        object.put("blogCount",PageInfo.getTotal());
        return object.toJSONString();
    };

    /***
     * 博客推荐列表
     * @return
     */
    @GetMapping("queryAll/Recommend")
    public String queryRecommendBlog(){
        JSONObject object=new JSONObject();
        object.put("RecommendBlogList",blogService.queryRecommendBlog());
        return  object.toJSONString();
    };

    /**
     * 博客游览
     * @param blogId
     * @param request
     * @return
     */
    @GetMapping("/{blogId}")
    public String queryById(@Param("博客ID") @PathVariable("blogId")Long blogId, HttpServletRequest request) {
        JSONObject object=new JSONObject();
        Blog blog=blogService.queryByIdBlog(blogId);
        System.out.println("====="+blog);
        object.put("Blog",blog);
        Views views=new Views();
        //获取用户ip
        String ip= IpUtils.getIpAddr(request);
        views.setBlogId(blogId).setIp(ip);
        viewsService.addViews(views);
        return object.toJSONString();
    }

    /***
     * 测试RedisHttpSession共享
     * @param session
     * @return
     */
    @GetMapping("/getuid")
    public String getSessionuid(HttpSession session){
        JSONObject object=new JSONObject();
        String id=session.getAttribute("uid").toString();
        System.out.println("uid:=================="+id);
        Long uid=Long.parseLong(id);
        object.put("uid",uid);
        object.put("sessionId",session.getId());
        return object.toJSONString();
    }


    @GetMapping("/blogs/{uid}")
    public String queryByuIdBlog(@PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        //验证是否登录
        User user=checkUser(uid);
        if(user!=null){
            List<Blog> blogs=blogService.queryByuIdBlog(user.getUid());
            log.info("查询到用户所发布的相关博客信息数量为:{}",blogs.size());
            object.put("blogs",blogs);
            return  object.toJSONString();
        }else{
            object.put("error","用户未登录");
            return  object.toJSONString();
        }
    }
    @GetMapping("/pageBlogs/{pageNumber}/{pageSize}/{uid}/{title}")
    public String queryByuIdPageBlog(HttpSession session,
                                     @Param("开始页数") @PathVariable("pageNumber") Integer pageNumber,
                                     @Param("总页数") @PathVariable("pageSize") Integer pageSize,
                                     @Param("用户Id") @PathVariable("uid") Long uid,
                                     @Param("查询条件")@PathVariable("title") String title){
        JSONObject object=new JSONObject();
        if(uid!=null){
            PageInfo<Blog> PageInfo =blogService.queryPageByuIdBlog(pageNumber,pageSize,uid,title);
            log.info("查询到用户所发布的相关博客信息数量为:{}",PageInfo.getTotal());
            object.put("total",PageInfo.getTotal());
            object.put("blogs",PageInfo.getList());
            object.put("flag",PageInfo.getList()!=null);
            return  object.toJSONString();
        }
            object.put("error","用户未登录");
            return  object.toJSONString();
    }

    @PutMapping("/UpdateBlog/{blogId}/state/{recommend}")
    public String UpdateBlog(@Param("博客id") @PathVariable("blogId") Long blogId,
                             @Param("推荐状态") @PathVariable("recommend") Boolean recommend){
        JSONObject object=new JSONObject();
        Blog blog=blogService.queryByIdBlog(blogId);
        blog.setRecommend(recommend);
       int i= blogService.UpdateBlog(blog);
       object.put("flag",i==1);
       return object.toJSONString();
    }

    @DeleteMapping("del/{blogId}")
    public String delBlog(@Param("博客Id") @PathVariable("blogId") Long blogId){
        JSONObject object=new JSONObject();
        object.put("flag",blogService.DelBlogById(blogId));
        return object.toJSONString();
    }

    public static void main(String[] args) {

        String password = "123456";
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();

        //加密：bcryptPasswordEncoder进行密码加密
        String encodedPassword = bcryptPasswordEncoder.encode(password);
        System.out.println("bcryptPasswordEncoder进行密码加密:"+encodedPassword);

        //解密：
        boolean flag = bcryptPasswordEncoder.matches(password, encodedPassword);
        //如果flag为true，则解密成功  false，则解密失败
        System.out.println("解密："+flag);

    }
}
